package com.xq.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xq.result.Result;
import com.xq.utils.JwtUtils;
import io.jsonwebtoken.JwtBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //生成Token
        String username = authentication.getName();
        JwtBuilder token = JwtUtils.createToken(username);
        //返回Token
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(Result.success(token.compact())));
    }
}
